const Router = require("koa-router");

const { auth } = require("../middleware/auth.middleware");
const { validatorParams } = require("../middleware/general.middleware");
const { verifyAddressId } = require("../middleware/addr.middleware");
const { addrFormatError } = require("../constant/error.type");
const { create, findAll, update, remove, setDefault } = require("../controller/addr.controller");

// 实例化子路由对象
const router = new Router({ prefix: "/address" });

/**
 * 创建地址接口
 */
router.post(
  "/",
  auth,
  validatorParams(
    {
      consignee: "string",
      phone: { type: "string", format: /^1[3-9]\d{9}$/, required: true },
      address: "string",
    },
    addrFormatError,
  ),
  create,
);

/**
 * 获取用户的所有收货人地址接口
 */
router.get("/", auth, findAll);

/**
 * 根据地址id更新地址接口
 */
router.put(
  "/:id",
  auth,
  validatorParams(
    {
      consignee: "string",
      phone: { type: "string", format: /^1[3-9]\d{9}$/, required: true },
      address: "string",
    },
    addrFormatError,
  ),
  verifyAddressId,
  update,
);

/**
 * 根据地址id删除地址接口
 */
router.delete("/:id", auth, verifyAddressId, remove);

/**
 * 设置默认地址接口
 */
router.patch("/:id", auth, verifyAddressId, setDefault);

module.exports = router;
